package com.kzn.controller;


import cn.hutool.cron.task.Task;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kzn.entity.GlobalVar;
import com.kzn.entity.RoughTask;
import com.kzn.entity.TimeTag;
import com.kzn.service.IRoughTaskService;
import com.kzn.util.NonStaticResourceHttpRequestHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author sorclown
 * @since 2022-02-05
 */
@RestController
@RequestMapping("/api/rough-task")
public class RoughTaskController {
    private IRoughTaskService taskService;
    private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;


    @Autowired
    public RoughTaskController(IRoughTaskService roughTaskService,
                               NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler) {
        this.taskService = roughTaskService;
        this.nonStaticResourceHttpRequestHandler = nonStaticResourceHttpRequestHandler;
    }

    /**
     * 查询已经可用但是还没有被别人接取的子任务。
     *
     * @return 还没人接取的子任务列表，格式为Json。
     */
    @RequestMapping("/selectReadyTask")
    public String selectReadyTask() {
        //设置条件
        QueryWrapper<RoughTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.eq("status", -1);
        taskQueryWrapper.last("limit 50");
        List<RoughTask> list = taskService.list(taskQueryWrapper);
        //查询并返回
        return JSONUtil.parseArray(list).toString();
    }


    /**
     * 接取子任务
     *
     * @param taskId  要被接取的任务
     * @param crowdId 接取的 crowd
     * @return 是否接取成功。
     */
    @RequestMapping("/allotTaskByCrowdId")
    public boolean allotTaskByCrowdId(@RequestParam Integer taskId, @RequestParam Integer crowdId) {
        QueryWrapper<RoughTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("taskId", taskId);
        RoughTask task = taskService.getById(taskId);
        if (task.getCrowdId() == null) {
            if (null != taskId && null != crowdId) {
                UpdateWrapper<RoughTask> updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", taskId);
                updateWrapper.set("status", 0);
                updateWrapper.set("crowdId", crowdId);
                return taskService.update(updateWrapper);
            }
        }
        return false;
    }

    /**
     * 根据crowdId查询子任务
     *
     * @param crowdId 发起查询的 crowdId
     * @param status  限定要查询的 status 范围
     * @return 返回根据条件查询到的子任务列表，格式为Json。
     */
    @RequestMapping("/selectTaskByCrowd")
    public String selectTaskByCrowd(@RequestParam Integer crowdId, @RequestParam(required = false) Integer status) {
        QueryWrapper<RoughTask> taskQueryWrapper = new QueryWrapper<>();
        //如果没有 crowdId 则拒绝查询，返回null
        if (null != crowdId) {
            taskQueryWrapper.eq("crowdId", crowdId);
            //如果有status则只查询status要求的，如果没有则返回该 crowd 下所有 task。
            if (null != status) {
                taskQueryWrapper.eq("status", status);
            } else {
                taskQueryWrapper.eq("status", 0);
            }
            return JSONUtil.parseArray(taskService.list(taskQueryWrapper)).toString();
        } else {
            return null;
        }
    }


    /**
     * 上传结果
     *
     * @param timeTags 结果集
     * @param taskId   结果所属的子任务
     * @return
     */
    @RequestMapping("/uploadResult")
    public boolean uploadResultByTask(@RequestBody List<TimeTag> timeTags, @RequestParam Integer taskId) {
        if (null != timeTags && null != taskId) {
            return taskService.uploadResultByTask(timeTags, taskId);
        } else {
            return false;
        }
    }

    /**
     * 提交子任务
     *
     * @param taskId  子任务ID
     * @param crowdId 标注人员ID
     * @return 是否提交成功
     */
    @RequestMapping("/submit")
    public boolean submitTask(@RequestParam Integer taskId, @RequestParam Integer crowdId) {
        if (null != taskId && null != crowdId) {
            return taskService.submit(taskId, crowdId);
        } else {
            return false;
        }
    }


    @RequestMapping(value = "/video/{id}", method = RequestMethod.GET)
    public void videoPreview(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer id) throws Exception {

        //假如我把视频1.mp4放在了static下的video文件夹里面
        //sourcePath 是获取resources文件夹的绝对地址
        //realPath 即是视频所在的磁盘地址
        RoughTask task = taskService.getById(id);
        String resourcePath = GlobalVar.UPLOAD_PATH + "/" + task.getProjectName() + "/" + task.getSourceFilePath();


        Path filePath = Paths.get(resourcePath);
        if (Files.exists(filePath)) {
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }


}
